package com.swm.util;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.swm.mapper.StockMapper;
import com.swm.pojo.Stock;
import org.apache.ibatis.session.SqlSession;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 师文明
 * @data 2024/12/14 上午9:11
 **/

public class getStockData {
    //创建一个固定大小的线程池
    static ExecutorService executorService = Executors.newFixedThreadPool(10);

    static SqlSession sqlSession = SqlSessionUtil.openSession();
    static StockMapper mapper = sqlSession.getMapper(StockMapper.class);

    public static List<Stock> getStcokList() {
        List<Stock> stocks = mapper.selectAllStock();
        return stocks;
    }

    public static void main(String[] args) {
        System.out.println(new Date());
        //获取所有股票列表
        List<Stock> stcokList = getStcokList();
        System.out.println("开盘跌幅低于9%，收盘涨幅大于9%");

        for (Stock stock : stcokList) {
            executorService.execute(() -> {
                try {
                    getData(stock.getCode(), stock.getType());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
        // 关闭线程池，以优雅的方式
        executorService.shutdown();
        System.out.println("结束");
        System.out.println(new Date());
    }

    public static void getData(String code, int type) throws Exception {
        //http://push2his.eastmoney.com/api/qt/stock/trends2/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13&fields2=f51,f52,f53,f54,f55,f56,f57,f58&ut=fa5fd1943c7b386f172d6893dbfba10b&secid=0.002384
        // 连接到新浪财经接口
        String url = "http://push2his.eastmoney.com/api/qt/stock/trends2/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13&fields2=f51,f52,f53,f54,f55,f56,f57,f58&ut=fa5fd1943c7b386f172d6893dbfba10b&secid=" + type + "." + code;
        //String url = "http://push2his.eastmoney.com/api/qt/stock/trends2/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13&fields2=f51,f52,f53,f54,f55,f56,f57,f58&ut=fa5fd1943c7b386f172d6893dbfba10b&secid=1.605179";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Cookie", "qgqp_b_id=488de58836c5f30c189b9ad4c700b9f5; st_si=04137509447995; websitepoptg_api_time=1734056942833; st_asi=delete; HAList=ty-1-603999-%u8BFB%u8005%u4F20%u5A92%2Cty-0-002888-%u60E0%u5A01%u79D1%u6280%2Cty-0-002269-%u7F8E%u90A6%u670D%u9970%2Cty-0-000813-%u5FB7%u5C55%u5065%u5EB7%2Cty-0-002045-%u56FD%u5149%u7535%u5668%2Cty-0-300059-%u4E1C%u65B9%u8D22%u5BCC%2Cty-1-688605-N%u5148%u950B%2Cty-1-000001-%u4E0A%u8BC1%u6307%u6570; st_pvi=62081555482493; st_sp=2024-12-11%2010%3A26%3A42; st_inirUrl=https%3A%2F%2Fwww.baidu.com%2Flink; st_sn=60; st_psi=20241213164756225-113200301201-5528754653");
        // 从数据源获取实时股票数据
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        String data = response.toString();
        //System.out.println(data);
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.get("data") != null) {
            JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("data").toString());
            //System.out.println(jsonObject1);
           /* System.out.println(jsonObject1.get("preClose"));
            System.out.println(jsonObject1.get("prePrice"));*/
            String name = jsonObject1.get("name").toString();

            JSONArray trends = JSONArray.parse(jsonObject1.get("trends").toString());
            //昨收
            double preClose = Double.parseDouble(jsonObject1.get("preClose").toString());
            //当天最大值
            double max = -10;
            if (trends.size() > 2) {
                boolean isUp = true;
                //判断是否一直增长
                for (int i = 1; i < trends.size(); i++) {
                    String[] split = trends.get(i).toString().split(",");
                    double curPrince = Double.parseDouble(split[2]);
                    //System.out.println(split[0]);
                    String[] beSplit = trends.get(i - 1).toString().split(",");
                    double bePrince = Double.parseDouble(beSplit[2]);

                    if (curPrince < bePrince) {
                        isUp = false;
                    }

                    double v = (curPrince - preClose) / preClose;
                    max = max > v ? max : v;
                }

                //判读开盘跌幅低于-9%
                String[] split1 = trends.get(1).toString().split(",");
                double firPrince = Double.parseDouble(split1[2]);

                //读取收盘价格
                String[] split2 = trends.get(trends.size() - 1).toString().split(",");
                double lastPrince = Double.parseDouble(split2[2]);

                double v = firPrince - preClose;
                double v1 = v / preClose;

                double v2 = lastPrince - preClose;
                double v3 = v2 / preClose;

                if (v1 < -0.09 && v3 > -0.07 && v3 < -0.03) {
                    //if (v1 < 0 && v3 < 0.03 && v3 >0.01 && v3>=max) {
                    DecimalFormat df = new DecimalFormat("#.00");
                    System.out.println("股票：" + name);
                    //System.out.println("昨收：" + jsonObject1.get("preClose"));
                    //System.out.println("今开：" + firPrince);
                    System.out.println("当前：" + lastPrince);
                    String start = df.format(v1 * 100);
                    System.out.println("开盘涨跌" + Double.parseDouble(start) + "%");
                    String end = df.format(v3 * 100);
                    System.out.println("当前涨跌" + Double.parseDouble(end) + "%");
                }

                /*if(isUp){
                    System.out.println("股票："+name);
                    System.out.println("K线："+trends);
                }*/
                //{"code":"688766","market":1,"type":23,"status":0,"name":"普冉股份","decimal":2,"preSettlement":0.0,"preClose":123.48,"beticks":"33300|34200|54000|33300|34200|41400|46800|54000","trendsTotal":256,"time":1734311803,"kind":1,"prePrice":123.48,"trends":["2024-12-16 09:15,123.48,123.48,123.48,123.48,0,0.00,123.480","2024-12-16 09:16,123.50,127.64,128.25,123.50,0,0.00,123.480","2024-12-16 09:17,127.64,127.88,127.88,127.64,0,0.00,123.480"]}

            }
        }
    }

}
